import { Address, Button, Checkbox, Form, Input } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { useRequest } from 'taro-hooks'
import Icon from '../../components/icon-font'
import Layout from '../../components/layout'
import { ADDRESS_OPTIONS } from '../../constants'
import { addAddress, getAddress } from '../../services/user'
import './index.less'

const EditAddress = () => {
  // 创建表单实例
  const router = useRouter()
  const { id } = router.params

  const [form] = Form.useForm()
  const region = Form.useWatch('region', form)

  const { runAsync: addAddressFn, loading } = useRequest(addAddress, {
    manual: true,
  })
  const { runAsync: getAddressFn } = useRequest(getAddress, {
    manual: true,
  })

  const [isEdit, setIsEdit] = useState(false)
  const [showAddress, setShowAddress] = useState(false)

  useEffect(() => {
    if (id) {
      setIsEdit(true)
      // 这里应该根据 id 获取地址详情
      getAddressFn(id).then((res: any) => {
        const data = res.address
        const _data = {
          name: data.name,
          phone: data.phone,
          region: data.address.split(' ')[0],
          address: data.address.split(' ').slice(1).join(' '),
          isDefault: data.isDefault,
        }
        // 使用 form 实例设置表单值
        form.setFieldsValue(_data)
      })
    }
  }, [form, getAddressFn, id])

  // 处理省市区选择
  const handleRegionChange = (values: string[], _options: any[]) => {
    // setRegionCode(values)
    const regionText = _options.map((item) => item.text).join('')

    // 使用 form 实例更新 region 字段
    form.setFieldsValue({ region: regionText })
  }

  // 打开省市区选择器
  const openAddressSelector = () => {
    setShowAddress(true)
  }

  // 关闭省市区选择器
  const closeAddressSelector = () => {
    setShowAddress(false)
  }

  // 表单提交成功回调
  const handleSubmit = (values: any) => {
    console.log('表单提交:', values)

    const data = {
      id: id,
      ...values,
      address: `${values.region} ${values.address}`,
    }

    addAddressFn(data)
      .then(() => {
        Taro.showToast({
          title: isEdit ? '地址更新成功' : '地址添加成功',
          icon: 'success',
        })
        // 延迟返回上一页
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      })
      .catch((error) => {
        Taro.showToast({
          title: error.message || '操作失败',
          icon: 'error',
        })
      })
  }

  // 表单验证失败回调
  const handleSubmitFailed = (error: any) => {
    console.log('表单验证失败:', error)

    // 提取第一个错误信息并提示
    const firstError = error?.errorFields?.[0]?.errors?.[0]
    if (firstError) {
      Taro.showToast({
        title: firstError,
        icon: 'none',
      })
    }
  }

  return (
    <Layout title={isEdit ? '编辑地址' : '添加地址'} showTabBar={false}>
      <View className='edit-address'>
        <Form
          form={form}
          onFinish={handleSubmit}
          onFinishFailed={handleSubmitFailed}
          className='address-form'
          initialValues={{
            name: '',
            phone: '',
            region: '',
            address: '',
            isDefault: false,
          }}>
          <View className='form-section'>
            <Form.Item
              label={
                <Text>
                  <Icon name='tianxuangouren' /> 收货人
                </Text>
              }
              name='name'
              rules={[
                { required: true, message: '请输入收货人姓名' },
                { min: 2, message: '姓名至少2个字符' },
              ]}>
              <Input placeholder='请输入收货人姓名' />
            </Form.Item>

            <Form.Item
              label={
                <Text>
                  <Icon name='tianxuangouren' /> 手机号
                </Text>
              }
              name='phone'
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
              ]}>
              <Input placeholder='请输入手机号' type='number' maxLength={11} />
            </Form.Item>
          </View>

          <View className='form-section'>
            <Form.Item label='省市区' name='region' rules={[{ required: true, message: '请选择省市区' }]}>
              <View className='region-selector' onClick={openAddressSelector}>
                <Input placeholder='请选择省市区' readOnly value={region} />
              </View>
            </Form.Item>

            <Form.Item
              label='详细地址'
              name='address'
              rules={[
                { required: true, message: '请输入详细地址' },
                { min: 5, message: '详细地址至少5个字符' },
              ]}>
              <Input placeholder='请输入街道、门牌号等详细地址' type='textarea' />
            </Form.Item>

            <Form.Item name='isDefault' valuePropName='checked'>
              <View className='checkbox-item'>
                <Checkbox />
                <Text className='checkbox-label'>设为默认地址</Text>
              </View>
            </Form.Item>
          </View>

          <View className='submit-section'>
            <Button type='primary' size='large' block formType='submit' loading={loading}>
              {isEdit ? '更新地址' : '添加地址'}
            </Button>
          </View>
        </Form>

        {/* 省市区选择器弹窗 */}
        <Address
          options={ADDRESS_OPTIONS}
          visible={showAddress}
          onClose={closeAddressSelector}
          onChange={handleRegionChange}
        />
      </View>
    </Layout>
  )
}

export default EditAddress
